<?php
// +----------------------------------------------------------------------
// | CLTPHP.Pro [会员模型]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2029 https://www.cltphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://www.cltphp.com/detail-140.html )
// +----------------------------------------------------------------------
// | Author: chichu <1109305987@qq.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Exception;
use think\facade\Cache;
use think\facade\Db;

class Users extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $validate = 'Users';

    public static function changeMobile($user, $mobile, $check_code)
    {
        //验证code是否合法
        $exist_code = Cache::store('redis')->get('check_code_' . $user['id']);
        if (empty($exist_code) || $exist_code != $check_code) {
            throw new UserException('验证参数不合法');
        }
        //验证手机号是否已经注册过
        $u = self::getByMobile($mobile);
        if (!empty($u)) {
            throw new UserException('手机号已经绑定过');
        }
        $user->mobile = $mobile;
        if (!$user->save()) {
            throw new UserException('更换成功');
        }
    }

    //验证用户
    public static function checkUser($user, $mobile, $password)
    {
        if ($user['mobile'] != $mobile) {
            throw new UserException('手机号错误');
        }

        if ($user['password'] != md5($user['salt'] . $password . $user['salt'])) {
            throw new UserException('密码错误');
        }
        $check_code = md5(time());
        Cache::store('redis')->set("check_code_" . $user['id'], $check_code);
        return $check_code;
    }

    public static function modifyPassword($mobile, $v_code, $new_password)
    {
        $user = self::getByMobile($mobile);
        if (empty($user)) {
            throw new UserException('用户不存在');
        }
        //验证验证码
        Sms::checkCode($mobile, $v_code, SMS::SMS_PASSWORD);
        $password = md5($user['sale'] . $new_password . $user['salt']);
        $user->password = $password;
        $user->login_time = time();
        $res = $user->save();
        if (empty($res))
            throw new UserException('更改失败');
    }

    //用户登录
    public static function loginPwd($mobile, $password)
    {
        $user = self::getByMobile($mobile);
        if (empty($user)) {
            throw new UserException('用户不存在');
        }
        if ($user['password'] != md5($user['salt'] . $password . $user['salt'])) {
            throw new UserException('密码错误');
        }
        $user->login_time = time();
        $token = self::toToken($user);
        $user->token = $token;
        $user->save();
        return $token;
    }

    //用户验证码登录/注册
    public static function loginCode($mobile, $code)
    {
        $user = self::getByMobile($mobile);
        //验证验证码是否成功
        Sms::checkCode($mobile, $code, Sms::SMS_LOGIN);
        if (empty($user)) {
            //用户不存在
            $user_data = [
                "mobile" => $mobile,
                "login_time" => time(),
                "password" => md5(time())
            ];
            $user = self::create($user_data);
        }
        $token = self::toToken($user);
        $user->token = $token;
        $user->save();
        return $token;
    }


    public static function fromToken($token)
    {
        $user_data = aes_decrypt($token);
        $user_info = json_decode($user_data, true);
        $r_token = Cache::store('redis')->get("access_token-" . $user_info['id']);
        if ($token != $r_token) {
            throw new TokenException('用户登录失效');
        }
        $user = self::find($user_info['id']);
        if ($user['password'] != $user_info['password']) {
            throw new TokenException('登录失效');
        }
        return $user;
    }


    public static function toToken($user)
    {
        $encrypt_data = [
            "id" => $user['id'],
            "password" => $user['password'],
            "login_time" => $user["login_time"]
        ];
        $token = aes_encrypt(json_encode($encrypt_data));
        Cache::store('redis')->set("access_token-" . $user['id'], $token);
        return $token;
    }

    public static function register($mobile, $code, $password, $invite_code)
    {
        if (!empty($invite_code)) {
            $parent = self::where('invite_code', $invite_code)->find();
            if (empty($parent)) {
                throw new Exception('邀请码不存在');
            }
            $parent_id = $parent['id'];
            $parent_id2 = $parent['parent_id'];
            $rpath = $parent['rpath'] . "," . $parent['id'];
            $rlevel = $parent['rlevel'] + 1;
        } else {
            $parent_id = 0;
            $parent_id2 = 0;
            $rpath = '0';
            $rlevel = 0;
        }

        $salt = generate_random_id();
        $user_data = [
            'username' => show_star($mobile, 3, 4),
            'password' => md5($salt . $password . $salt),
            'salt' => $salt,
            'mobile' => $mobile,
            'invite_code' => generate_random_id(),
            'parent_id' => $parent_id,
            'parent_id2' => $parent_id2,
            'rpath' => $rpath,
            'rlevel' => $rlevel
        ];
        Sms::checkCode($mobile, $code, Sms::SMS_REGISTER);
        $user = self::create($user_data);
        return $user;
    }

    // 一对一获取所属分组
    public function userLevel()
    {
        return $this->belongsTo('UserLevel', 'level_id');
    }

    // 获取字段列表
    public static function getList($where = array(), $page, $order = ['sort', 'create_time' => 'desc'])
    {
        $list = self::where($where)->order($order)->paginate($page);
        return $list;
    }

}